package com.taglab.chic.taglib;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;

/**
 * Google Analytics tag useful for adding user tracking to a page.
 *
 * Recomend putting this as the last tag before &lt;/body&gt;.
 *
 * XXX this is still very early stages, likley to change.
 *
 * @author Markus Kobler
 */
public class GoogleAnalyticsTag extends TagSupport {

//  private final static Logger logger = LoggerFactory.getLogger(GoogleAnalyticsTag.class);

  public final static String DEFAULT_TRACKER_NAME = "pageTracker";

  private boolean disabled = false;
  private String trackerName = DEFAULT_TRACKER_NAME;
  private String trackerCode;

  public void setTrackerName(String trackerName) {
    // XXX validate for illegal javascript names
    this.trackerName = trackerName.trim();
  }

  public void setTrackerCode(String trackerCode) {
    this.trackerCode = trackerCode.trim();
  }

  public void setDisabled(boolean disabled) {
    this.disabled = disabled;
  }

  @Override
  public int doStartTag() throws JspException {
    if(disabled) return SKIP_BODY;

    if( trackerCode == null )
      throw new IllegalStateException("Tracker code not set");

    try {
      JspWriter out = pageContext.getOut();
      out.write("<script type=\"text/javascript\">\n");
      out.write("var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");\n");
      out.write("document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));\n");
      out.write("</script>\n<script type=\"text/javascript\">\n");
      out.write("try {\n");
      out.write("  var ");
      out.write(trackerName);
      out.write(" = _gat._getTracker(\"");
      out.write(trackerCode);
      out.write("\");\n");

      // share for any inner trackerCode
      setValue("trackerName", trackerName);
      setValue("trackerCode", trackerCode);

      return EVAL_BODY_INCLUDE;
    } catch (IOException e) {
      throw new JspException(e.toString(), e);
    }
  }


  @Override
  public int doEndTag() throws JspException {
    if(disabled) return SKIP_BODY;

    try {
      JspWriter out = pageContext.getOut();

      // XXX Should trackPageview() always be called?
      out.write("  ");
      out.write(trackerName);
      out.write("._trackPageview();\n");
      
      out.write("} catch(err) {}\n");      
      out.write("</script>");      
      return EVAL_PAGE;
    } catch (IOException e) {
      throw new JspException(e.toString(), e);
    }
  }

}
